(function () {
    if (localStorage.getItem("rememberMe") === "0") {
        token = sessionStorage.getItem("token")
        userName = sessionStorage.getItem("userName")
        userIdP = sessionStorage.getItem("userIdP")
    } else {
        token = localStorage.getItem("token")
        userName = localStorage.getItem("userName")
        userIdP = localStorage.getItem("userIdP")
    }
    getVersion();
    initPatients(0, 5);
})();

function getVersion() {
    $.ajax({
        url: "/user/queryVersion/" + userIdP,
        type: "GET",
        success: function (data) {
            version = data.data;
        }
    })

}


//格式化页面分页
function initPatients(currentPage, rows) {
    $.ajax({
        url: "/file/getFile",
        type: "POST",
        dataType: 'json',
        headers: {"Content-Type": "application/json;charset=utf-8", 'Authorization': token},
        data: JSON.stringify({
            currentPage: currentPage,
            rows: rows,
            userId: userIdP
        }),
        success: function (data) {
            if (data.code === 20001){
                location.href = encodeURI("../login.html")
            }else {
                localStorage.setItem("Page", "1");
                $("tbody").empty();
                var index = (currentPage) * 5 + 1;
                data.data.list.forEach(info => {
                    showData(info.fileId, info.fileName, info.fileUrl,
                        info.createTime);
                });
                $("#pageUl").empty();
                showPage(data.data.totalPage);
            }

        },
        error() {
            location.href = encodeURI("../login.html")
        }
    });

}

//按页数分页
function findByPage(currentPage, rows) {
    $.ajax({
        url: "/file/getFile",
        type: "POST",
        dataType: 'json',
        headers: {"Content-Type": "application/json;charset=utf-8", 'Authorization': token},
        data: JSON.stringify({
            currentPage: currentPage,
            rows: rows,
            userId: userIdP
        }),
        success: function (data) {
            if (data.code === 20001){
                location.href = encodeURI("../login.html")
            }
            $("tbody").empty();
            var index = currentPage + 1;
            data.data.list.forEach(info => {
                showData(info.fileId, info.fileName, info.fileUrl,
                    info.createTime);
            });
        }, error() {
            location.href = encodeURI("../login.html")
        }
    });
}

//展示分页栏
function showPage(totalPage) {
    var ul = $("#pageUl");
    ul.append(
        "<li class=\"page-item\">" +
        "<a class=\"page-link\" href=\"javascript:void(0)\" aria-label=\"Previous\" id='previousPage' onclick='previousPage()'>" +
        "<span aria-hidden=\"true\">&laquo;</span>" +
        "</a>" +
        "</li>"
    )
    for (let i = 1; i <= totalPage; i++) {
        if (i === 1) {
            ul.append(
                "<li class=\"page-item active indexPage\"><a class=\"page-link\" href=\"javascript:void(0)\" onclick='changePage(this)'>" +
                i
                + "</a></li>"
            )
            continue;
        }
        ul.append(
            "<li class=\"page-item indexPage\"><a class=\"page-link\" href=\"javascript:void(0)\" onclick='changePage(this)'>" +
            i
            + "</a></li>"
        )
    }
    ul.append(
        "<li class=\"page-item\">" +
        "<a class=\"page-link \" href=\"javascript:void(0)\" aria-label=\"Next\" id='nextPage' onclick='nextPage()'>" +
        "<span aria-hidden=\"true\">&raquo;</span>\n" +
        "</a>\n" +
        "</li>"
    )
}

//前进分页
function previousPage() {
    var ip = $(".indexPage");
    for (let i = 0; i < ip.length; i++) {
        if (ip[i].classList.contains("active")) {
            if (i > 0) {
                ip[i].classList.remove("active");
                ip[i - 1].classList.add("active")
                var index = ip[i - 1].innerText;
                localStorage.setItem("Page", index)
                if ($("#queryName")[0].classList.contains("haveInfo")) {
                    queryChange((index - 1) * 5, 5);
                } else {
                    findByPage((index - 1) * 5, 5);
                }
            }
            break;
        }
    }
}

//后退分页
function nextPage() {
    var ip = $(".indexPage");
    for (let i = 0; i < ip.length; i++) {
        if (ip[i].classList.contains("active")) {
            if (i < ip.length - 1) {
                ip[i].classList.remove("active");
                ip[i + 1].classList.add("active")
                var index = ip[i + 1].innerText;
                localStorage.setItem("Page", index)
                if ($("#queryName")[0].classList.contains("haveInfo")) {
                    queryChange((index - 1) * 5, 5);
                } else {
                    findByPage((index - 1) * 5, 5);
                }
            }
            break;
        }
    }
}

//改变页数
function changePage(item) {
    if ($("#queryName")[0].classList.contains("haveInfo")) {
        queryChange(($(item).text() - 1) * 5, 5);
    } else {
        findByPage(($(item).text() - 1) * 5, 5)
    }
    var ip = $(".indexPage");
    for (let i = 0; i < ip.length; i++) {
        if (ip[i].classList.contains("active")) {
            ip[i].classList.remove("active")
            break;
        }
    }
    $(item).parent("li").addClass("active")
    localStorage.setItem("Page", $(item).text())
}

//显示数据
function showData(fileId, fileName, fileUrl, createTime) {
    $("tbody").append(
        "<tr>" +
        "<td>" +
        "<input class='checkItem' type='checkbox'>" +
        "</td>" +
        "<td>" + fileId + "</td>" +
        "<td>" + fileName + "</td>" +
        "<td>" +
        "<a class=\"dropdown-item logout\" style='color: #80bdff' href= " + fileUrl + ">" + fileUrl + "</a>" +
        "</td>" +
        "<td>" + new Date(+new Date(new Date(createTime).toJSON()) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '') + "</td>" +
        "<td hidden>" + "<input type='text' class='pId' hidden value=" + fileId + ">" + "</td>" +
        "</tr>");
}

//多条件分页查询
$("#queryPatient").click(function () {
    var queryName = $("#queryName");
    var queryInfo = queryName.val();
    if (queryInfo != null && queryInfo !== "") {
        //存储数据
        localStorage.setItem("queryName", queryName.val());
        queryName.addClass("haveInfo");
        $.ajax({
            url: "/file/findFile",
            type: "POST",
            dataType: 'json',
            headers: {"Content-Type": "application/json;charset=utf-8", 'Authorization': token},
            data: JSON.stringify({
                queryName: "%" + queryName.val() + "%",
                currentPage: 0,
                rows: 5,
                userId: userIdP
            }),
            success: function (data) {
                if (data.code === 20001){
                    location.href = encodeURI("../login.html")
                }
                if (data.code === 200) {
                    $("tbody").empty();
                    var index = 1;
                    data.data.list.forEach(info => {
                        showData(info.fileId, info.fileName, info.fileUrl,
                            info.createTime);
                    });
                    $("#pageUl").empty();
                    showPage(data.data.totalPage);
                }
            }, error() {
                location.href = encodeURI("../login.html")
            }
        })
    }
})
//显示全部
$("#findAllP").click(function () {
    $("#queryName")[0].classList.remove("haveInfo");
    localStorage.removeItem("queryName");
    initPatients(0, 5);
})

//查询切换页面
function queryChange(currentPage, rows) {
    var queryName = localStorage.getItem("queryName");
    $.ajax({
        url: "/file/findFile",
        type: "POST",
        dataType: 'json',
        headers: {"Content-Type": "application/json;charset=utf-8", 'Authorization': token},
        data: JSON.stringify({
            queryName: "%" + queryName + "%",
            currentPage: currentPage,
            rows: rows,
            userId: userIdP
        }),
        success: function (data) {
            if (data.code === 200) {
                $("tbody").empty();
                var index = currentPage + 1;
                data.data.list.forEach(info => {
                    showData(info.fileId, info.fileName, info.fileUrl,
                        info.createTime);
                });
            }
        }, error() {
            location.href = encodeURI("../login.html")
        }
    })
}


//全选
$("#select-all").click(function () {
    if ($("#select-all")[0].checked) {
        $("td input:checkbox").prop("checked", true);
    } else {
        $("td input:checkbox").prop("checked", false);
    }
})

//删除
$('#delPatient').click(function () {
    if (version > 2) {
        if (confirm('你确认删除吗？？')) {
            var delList = [];
            $("tbody tr").each(function (i) {
                // 遍历 tr
                let ttd = $(this).children('td').children("input");
                if (ttd[0].checked) {
                    delList.push(ttd[1].value);
                }
            });
            $.ajax({
                url: "/file/delFile",
                type: "DELETE",
                dataType: 'json',
                headers: {"Content-Type": "application/json;charset=utf-8", 'Authorization': token},
                data: JSON.stringify(
                    delList
                ),
                success: function (result) {
                    if (result.code === 200) {
                        $("select-all").prop("checked", false)
                        var currentPage = localStorage.getItem("Page");
                        if ($("#queryName")[0].classList.contains("haveInfo")) {
                            queryChange((currentPage - 1) * 5, 5);
                        } else {
                            findByPage((currentPage - 1) * 5, 5);
                        }
                        alert("操作完成");
                    }

                }, error() {
                    alert("操作异常")
                    location.href = encodeURI("../login.html")
                }
            })
        }
    } else {
        alert("权限不足")
    }
})


